var $ = getApp(), methods = require("../methods.js");
Page(Object.assign({}, methods, {
	data: {
    showIndex:null,//打开弹窗的对应下标
    height:'',//屏幕高度
    fistOn:1,//初次进入微信小程序
    xieyiContent:'',//协议内容
    options: [],
    region:[],
    address:'',
		id: 0,//#marker
		pageinfo: [],
		pagecontent: [],
        hideguanggao:0,
        diaoyouquanlist:[],
        diaoyouquancate:[],
        cid:0,
        useraddressstr:"",
        showbox:false,
        showQun:false,
        dyqewm:'',
        input1:'',
        input2:'',
	},
	_onLoad: function (options) {
    this.fist()
  //   // 打开调试 TODO
	// wx.setEnableDebug({
	//   enableDebug: true
	// })
	
	// // 关闭调试
	// wx.setEnableDebug({
	//   enableDebug: false
	// })
  // Tips

  
		var that = this
		var id = 0;
		if (options && options.id) {
			id = options.id
			that.setData({ id: id, options: options })
    }
    // 
    
		if (options && options.scene) {
			var scenes = options.scene.split('_');
			if(scenes[1]){
				id = parseInt(scenes[1]);
				that.setData({ id: id, options: options });
			}
		}
		$.get('index/index', { id: that.data.id }, function (data) {
			if(data.status == 2){//付费查看
				$.goto('/pages/wxpay/pagepay?fromPage=index&orderid='+data.orderid+'&pageid='+that.data.id,'redirect');
				return;
			}
			if (data.status == 1) {
				var pagecontent = data.pagecontent
				var _bannerindex = [];
				for(var i in pagecontent){
					_bannerindex[i] = 0;
				}
				data.sysset.textset = that.data.textset
				that.setData({ 
                    title: data.pageinfo.title,
                    sysset: data.sysset,
                    oglist: data.oglist,
                    guanggaopic:data.guanggaopic,
                    guanggaourl:data.guanggaourl,
                    pageinfo: data.pageinfo, 
                    pagecontent: pagecontent,
                    _bannerindex:_bannerindex,
                    diaoyouquanlist:data.diaoyouquanlist,
                    diaoyouquancate:data.diaoyouquancate,
                    cid:data.diaoyouquancate[0].id
                })
				wx.setNavigationBarTitle({ title: data.pageinfo.title })
			} else {
				if(data.msg){
					$.alert(data.msg,function(){
						if(data.url) $.goto(data.url)
					});
				}else if(data.url){
					$.goto(data.url)
				}else{
					$.alert('您无查看权限');
				}
			}
		}),this.onLocation();
    },
    // 判断是否初次登录微信小程序
    fist(){
      let that = this
      // wx.getStorageSync('key', data)
      if(wx.getStorageSync('fist', this.data.fistOn)){
        return
      }else{
        that.openPopup()
        $.post('/yuxun/getFirstAgreement',{},res =>{
          console.log('res111',res)
          this.setData({xieyiContent:res.content})
        })
        
      }
    },
     // 打开弹窗
  openPopup(){
    // var index = e.currentTarget.dataset.index;
    // console.log('openPopup111',index)
    this.setData({
      showIndex:"1"
    })
  },
  //关闭弹窗
  closePopup(){
    this.setData({
      showIndex:null
    })
    wx.setStorageSync('fist', this.data.fistOn)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var that = this;
    // 动态获取屏幕高度
    wx.getSystemInfo({
      success: (result) => {
        that.setData({
          height: result.windowHeight
        });
      },
    })
  },
    // 提交申请
    confirm(){
      let that = this
      $.post('Diaochang/ruzhu',{diaochang_name:that.data.input1,address:that.data.address,tel:that.data.input2},function(res){
        wx.showToast({
          title: '提交成功',
        })
        that.setData({showapplybox:false})
      })
    },
  // 选择地区
  bindRegionChange: function (e) {
   
    const str = e.detail.value.join(',')
    this.setData({
      region: e.detail.value,
      address:str
    })
    console.log('picker发送选择改变，携带值为',this.data.address, e.detail.value)
  },
      // 输入框
  inputChange1: function(e) {
    // 当输入框的值发生变化时触发该函数
    // 更新data中的inputValue，实现单向数据绑定
    this.setData({
      input1: e.detail.value
    });
    console.log('input1',this.data.input1)
  },
  inputChange2: function(e) {
    // 当输入框的值发生变化时触发该函数
    // 更新data中的inputValue，实现单向数据绑定
    this.setData({
      input2: e.detail.value
    });
    console.log('input2',this.data.input2)
  },
    //获取用户定位
  onLocation(){
    var that = this;
    // var regionData = $.getCache('regionData');
    // if(!regionData){
    //   $.get("/region/list",{},function(res){
    //     regionData = res.data;
    //     $.setCache('regionData', res.data);
    //   })
    // }

    var select_address = $.getCache("select_address");
    var useraddress = $.getCache("useraddress") || '';
    if(select_address && useraddress){
      that.setData({useraddressstr:select_address});
      return;
    }

    var QQMapWx = require('../../base/qqmap-wx-jssdk.js');
    var qqMapsdk = new QQMapWx({
      key: 'OTTBZ-LAH6U-COHVX-BWRZS-VWYX7-4EFZ5', // 生成的秘钥
    });

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.getLocation({
                type: 'gcj02',
                success(res) {
                  console.log('定位：lat:'+res.latitude+" lng:"+res.longitude);
                  qqMapsdk.reverseGeocoder({
                    location: {
                      latitude: res.latitude,
                      longitude: res.longitude
                    },
                    success(elem) {
                      const { result: { address_component: { province, city, district } } } = elem // 省市区
                      // console.log(3333)
                      // console.log(province)
                      var useraddress = {
                        province_name:province,
                        city_name:city,
                        district_name:district,
                        latitude:res.latitude,
                        longitude:res.longitude
                      }
                      // that.setData({address:address})
                      $.setCache("useraddress",useraddress);
                      var useraddressstr = province+city;
                    $.setCache("select_address",useraddressstr);
                    that.setData({useraddressstr,useraddressstr});
                    /*
                      for(var i=0; i<regionData.length;i++){
                        for(var j=0;j<regionData[i].data.length;j++){
                          if(city == regionData[i].data[j].name){
                            console.log(regionData[i].data[j]);
                            that.setData({address:regionData[i].data[j]});
                            $.setCache("select_address",regionData[i].data[j])
                          }
                        }
                      }*/
                    },
                    fail: (res) => {
                      console.log(res)
                    }
                  })
                }
              })
            }
          })
        } else {
          wx.getLocation({
            type: 'gcj02',
            success(res) {
              console.log('定位2：lat:'+res.latitude+" lng:"+res.longitude);

              qqMapsdk.reverseGeocoder({
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude
                },
                success(elem) {
                  const { result: { address_component: { province, city, district } } } = elem // 省市区
                  // console.log(3333)
                   console.log(province + city + district)
                  var useraddress = {
                    province_name:province,
                    city_name:city,
                    district_name:district,
                    latitude:res.latitude,
                    longitude:res.longitude,
                  }
                  // that.setData({address:address})
                  $.setCache("useraddress",useraddress);
                  var useraddressstr = province+city;
                  $.setCache("select_address",useraddressstr);
                  that.setData({useraddressstr,useraddressstr});
                  /*
                  for(var i=0; i<regionData.length;i++){
                    for(var j=0;j<regionData[i].data.length;j++){
                      if(city == regionData[i].data[j].name){
                        console.log(regionData[i].data[j])
                        that.setData({address:regionData[i].data[j]});
                        $.setCache("select_address",regionData[i].data[j])
                      }
                    }
                  }*/
                },
                fail: (res) => {
                  console.log(res)
                }
              })
            }
          })
        }
        
      }
    })
  },
  showbox:function(){
        this.setData({showbox:true})
    },
    hidebox:function(){
        this.setData({showbox:false})
    },
    showQunBox:function(){
        this.setData({showQun:true});
    },
    hideQunBox:function(){
        this.setData({showQun:false});
    },
    //
    changeCate(e){
        var that = this;
        var cid = e.currentTarget.dataset.cid;
        $.post('luntan/ltlist', { cid: cid}, function (res) {
            if(res.status==1){
                that.setData({
                    diaoyouquanlist:res.datalist,
                    cid:cid
                })
                
            }else{
                $.error(res.msg);return false;
            }
        })
    },
    zan:function(e){
        var that = this;
        var id = e.currentTarget.dataset.id;
         // 获取当前项的索引
        const index = this.data.diaoyouquanlist.findIndex(item => item.id === id)
        $.post('luntan/zan', { id: id}, function (res) {
            if(res.status==1){
                // 取反当前项的点赞状态
                if(res.type==1){
                    that.setData({
                        [`diaoyouquanlist[${index}].zan`]: that.data.diaoyouquanlist[index].zan+1,
                        [`diaoyouquanlist[${index}].islike`]: 1
                     })
                }else{
                    that.setData({
                        [`diaoyouquanlist[${index}].zan`]: that.data.diaoyouquanlist[index].zan-1,
                        [`diaoyouquanlist[${index}].islike`]: 0
                     })
                }
                // 判断当前项是否已点赞
                const className = res.type ? 'like' : ''
                const selector = `.list-item:nth-child(${index + 1}) .zan`
                const btn = that.selectComponent(selector)
                btn && btn.setData({ className })
                
            }else{
                $.error(res.msg);return false;
            }
        })
    },
	closegg:function(){
		this.setData({hideguanggao:1})
	}
}));